import React, {useEffect, useRef, useState} from 'react';
import {Avatar, Button, Form, Input, message, Pagination, Popconfirm, Select, Table} from "antd";
import {AntDesignOutlined, SearchOutlined, SyncOutlined} from "@ant-design/icons";
import {getBlogTypeListApi, getBlogTextListApi, deleteBlogApi, editBlogApi} from "./BlogContentApi";
import {useNavigate} from "react-router-dom";
import {timestampToTime} from "../../utils/dateTimeUtlis";

function BlogContent() {
    const [searchData, setSearchData] = useState({})
    const [tableData, setTableData] = useState([])
    const [total, setTotal] = useState(0)
    const [blogTypeList, setBlogTypeList] = useState([])
    const [loading, setLoading] = useState(false);
    const [messageApi, contextHolder] = message.useMessage();
    const Navigate = useNavigate()
    const [listQuery, setListQuery] = useState({page: 1, limit: 10})
    const formRef = useRef()

    const columns = [
        {
            title: '博客标题',
            key: 'blogTitle',
            dataIndex: 'blogTitle',
            align: 'center',
            width: '200px'
        },
        {
            title: '博客类型',
            key: 'blogTypeNameK',
            dataIndex: 'blogTypeNameK',
            align: 'center',
            width: '200px'
        },
        {
            title: '封面图片',
            key: 'blogCoverImage',
            dataIndex: 'blogCoverImage',
            align: 'center',
            width: '300px',
            render: (text) => {
                return (<Avatar
                    size={{xs: 24, sm: 32, md: 40, lg: 64, xl: 80, xxl: 100,}}
                    src={text}
                    icon={<AntDesignOutlined/>}
                />)
            }

        },
        {
            title: '浏览次数',
            key: 'blogPageView',
            dataIndex: 'blogPageView',
            align: 'center',
            width: '100px'
        },
        {
            title: '评论次数',
            key: 'blogCommentNumber',
            dataIndex: 'blogPageView',
            align: 'center',
            width: '100px'
        },
        {
            title: '状态',
            key: 'blogStatus',
            dataIndex: 'blogStatus',
            align: 'center',
            render: (text) => {
                if (text === '0' || text === 0) {
                    return <div>草稿</div>
                }
                if (text === '1' || text === 1) {
                    return <div>已发布</div>
                }
            }
        },
        {
            title: '创建日期',
            key: 'createdAt',
            dataIndex: 'createdAt',
            align: 'center',
            width: '250px',
            render: (text) => {
                return (
                    <div>{timestampToTime(text)}</div>
                )
            }
        },
        {
            title: '修改日期',
            key: 'updatedAt',
            dataIndex: 'updatedAt',
            align: 'center',
            width: '250px',
            render: (text) => {
                return (
                    <div>{timestampToTime(text)}</div>
                )
            }

        },
        {
            title: '操作',
            key: 'edit',
            align: 'center',
            fixed: 'right',
            render: (text) => {
                return (
                    <div style={{display: 'flex', justifyContent: "center"}}>
                        <Button type="link" onClick={() => editBlogFun(text)}>编 辑</Button>
                        <Popconfirm
                            title="删除确认"
                            description="是否删除该类型"
                            onConfirm={() => deleteBlogTypeFun(text)}
                            onCancel={cancel}
                            okText="Yes"
                            cancelText="No"
                        >
                            <Button type="link" danger>删 除</Button>

                        </Popconfirm>
                        <Button type="link"
                                disabled={text.blogStatus === 1}
                                style={{color: "orange"}}
                                onClick={() => issue(text)}>发 布</Button>
                    </div>


                )
            }
        }
    ]
    // 编辑
    const editBlogFun = (row) => {
        Navigate(`/HomeSystem/addBlog?id=${row.id}`)
    }
    // 取消
    const cancel = (e) => {
        messageApi.info('已取消删除');
    };
    // 删除
    const deleteBlogTypeFun = (row) => {
        deleteBlogApi({id: row.id}).then((res) => {
            if (res.code === '200') {
                messageApi.success('删除成功')
                getBlogTextList()
            }
        }).catch(e => {
            console.log(e)
        })
    }
    // 发布
    const issue = (row) => {
        const nowData = timestampToTime(new Date().getTime())
        const json = {
            editData: {id: row.id},
            reqData: {blogStatus: '1', blogReleaseDate: nowData}
        }
        editBlogApi(json).then((res) => {
            if (res.code === '200') {
                messageApi.success('发布成功')
                getBlogTextList()
            }
        }).catch(e => {
            console.log(e)
        })
    }
    // 查询
    const searchFun = () => {
        getBlogTextList()
    }
    // 输入框修改
    const inputChange = (e, name) => {
        setSearchData({...searchData, [name]: e.target.value})
    }
    // 重置
    const reset = () => {
        formRef.current.resetFields()
        setSearchData({})
        getBlogTextList({reqData: {}, listQuery})
    }
    // 分页
    const paginationChange = (page) => {
        setListQuery({...listQuery, page: page})
    }
    // 选择框修改
    const handleChange = (value) => {
        setSearchData({...searchData, blogTypeNameK: value})
    };
    // 请求数据
    const getBlogTextList = (data = null) => {
        const json = data || {searchData, listQuery}
        setLoading(true);
        getBlogTextListApi(json).then(res => {
            setTableData(res.data.rows)
            setTotal(res.data.count)
            setLoading(false)
        }).catch((e) => {
            console.log(e)
        })
    }

    // 页面初始化
    useEffect(() => {
        getBlogTypeListApi().then(res => {
            if (res.code === '200') {
                setBlogTypeList(res.data.rows.map(i => {
                    return {
                        value: i.blogTypeName,
                        label: i.blogTypeName
                    }
                }))
            }
        }).catch((e) => {
            console.log(e)
        })
    }, [])


    useEffect(() => {
        getBlogTextList()
    }, [listQuery])

    return (<div>
        <div style={{display: 'flex', width: '100%', position: "relative", marginBottom: '10px'}}>
            <div style={{marginRight: '20px', paddingRight: '20px', overflow: 'hidden'}}>
                <Form
                    name="basic"
                    layout="inline"
                    wrapperCol={{span: 18,}}
                    style={{maxWidth: '1000px',}}
                    initialValues={{remember: true,}}
                    autoComplete="off"
                    ref={formRef}
                >
                    <Form.Item
                        label="博客标题"
                        colon={true}
                        labelCol={{span: 8}}
                        name="blogTitle">
                        <Input onChange={(e) => inputChange(e, 'blogTitle')}/>
                    </Form.Item>
                    <Form.Item
                        labelCol={{span: 8}}
                        label="博客类型"
                        colon={true}
                        name="blogTypeNameK">
                        <Select
                            style={{width: '200px'}}
                            onChange={handleChange}
                            options={blogTypeList}
                        >
                        </Select>
                    </Form.Item>
                </Form>
            </div>
            <div>
                <Button onClick={searchFun} icon={<SearchOutlined/>} type="primary">查 询</Button>
                <div style={{width: '10px', display: 'inline-block'}}></div>
                <Button onClick={reset} icon={<SyncOutlined/>}>重 置</Button>
            </div>
        </div>
        <div>
            <Table columns={columns}
                   dataSource={tableData}
                   scroll={{x: 'max-content', y: 650}}
                   loading={loading}
                   rowKey={'id'}
                   bordered
                   pagination={false}/>
            <div style={{display: "flex", justifyContent: 'right', alignItems: 'center', marginTop: '10px'}}>
                <span style={{marginRight: '10px'}}>总数{total}条</span>
                <Pagination defaultCurrent={1}
                            current={listQuery.page}
                            pageSize={10}
                            total={total}
                            onChange={paginationChange}
                />
            </div>
            {contextHolder}
        </div>
    </div>);
}

export default BlogContent;
